package com.bruip.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bruip.reggie.common.BaseResponse;
import com.bruip.reggie.common.CustomException;
import com.bruip.reggie.pojo.User;
import com.bruip.reggie.service.UserService;
import com.bruip.reggie.util.SMSUtils;
import com.bruip.reggie.util.ValidateCodeUtils;
import javafx.scene.layout.BackgroundRepeat;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.awt.image.PNGImageDecoder;

import javax.servlet.http.HttpSession;
import java.sql.Struct;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 王若龙
 * @date 2022-10-11 19:32
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送手机验证码
     *
     * @param user 用户
     * @return {@link BaseResponse}<{@link String}>
     */
    @PostMapping("/sendMsg")
    public BaseResponse<String> sendMsg(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.isEmpty(phone)) {
            throw new CustomException("手机号为空");
        }
        //生成随机的验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("验证码：{}", code);
        //调用阿里云的API发送短信
//        SMSUtils.sendMessage("瑞吉外卖", "", phone, code);

        //将验证码存入session中，后续使用
//        session.setAttribute(phone, code);

        //将生成的验证码保存在redis中，设置有效期为5分钟
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

        return BaseResponse.success("短信验证码已发送");
    }

    @PostMapping("/login")
    public BaseResponse<User> login(@RequestBody Map<String, String> map, HttpSession session) {
        String phone = map.get("phone");
        String respCode = map.get("code");
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(respCode)) {
            throw new CustomException("手机号或验证码不能为空");
        }

//        String code = (String) session.getAttribute(phone);

        //从redis中获取验证码
        String code = (String) redisTemplate.opsForValue().get(phone);

        if (StringUtils.isEmpty(code)) {
            throw new CustomException("验证失败");
        }
        //验证短信验证码
        if (!code.equals(respCode)) {
            throw new CustomException("验证失败");
        }

        //判断是否为新用户，若果是，则自动完成注册
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            user = new User();
            user.setPhone(phone);
            userService.save(user);
        }
        session.setAttribute("user", user.getId());

        // 用户登录成功后，删除缓存的验证码
        redisTemplate.delete(phone);
        return BaseResponse.success(user);
    }

    @PostMapping("/logout")
    public BaseResponse<String> logout(HttpSession session){
        session.invalidate();
        return BaseResponse.success("退出登录");
    }
}
